package com.example.demo.service;

import com.example.demo.util.DBUtil;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
    
    public Map<String, Object> register(String username, String password, String userType) {
        Map<String, Object> result = new HashMap<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            logger.info("开始注册用户: {}", username);
            conn = DBUtil.getConnection();
            
            // 检查用户名是否已存在
            String checkSql = "SELECT COUNT(*) FROM users WHERE username = ?";
            ps = conn.prepareStatement(checkSql);
            ps.setString(1, username);
            rs = ps.executeQuery();
            
            if (rs.next() && rs.getInt(1) > 0) {
                logger.warn("用户名已存在: {}", username);
                result.put("success", false);
                result.put("message", "用户名已存在");
                return result;
            }

            // 插入新用户
            String insertSql = "INSERT INTO users (username, password, user_type) VALUES (?, ?, ?)";
            ps = conn.prepareStatement(insertSql);
            ps.setString(1, username);
            ps.setString(2, password);
            ps.setString(3, userType);
            
            int rows = ps.executeUpdate();
            if (rows > 0) {
                logger.info("用户注册成功: {}", username);
                result.put("success", true);
                result.put("message", "注册成功");
            } else {
                logger.error("用户注册失败，未插入数据: {}", username);
                result.put("success", false);
                result.put("message", "注册失败");
            }
        } catch (SQLException e) {
            logger.error("注册过程中发生SQL异常: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
        } catch (Exception e) {
            logger.error("注册过程中发生未知异常: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
        } finally {
            DBUtil.close(conn, ps, rs);
        }
        return result;
    }

    public Map<String, Object> login(String username, String password, String userType) {
        Map<String, Object> result = new HashMap<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            logger.info("开始用户登录: {}", username);
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM users WHERE username = ? AND password = ? AND user_type = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            ps.setString(3, userType);
            
            rs = ps.executeQuery();
            if (rs.next()) {
                logger.info("用户登录成功: {}", username);
                result.put("success", true);
                result.put("message", "登录成功");
                
                // 创建用户信息Map
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("id", rs.getLong("id"));
                userInfo.put("username", rs.getString("username"));
                userInfo.put("userType", rs.getString("user_type"));
                result.put("user", userInfo);
            } else {
                logger.warn("用户登录失败: {}", username);
                result.put("success", false);
                result.put("message", "用户名或密码错误");
            }
        } catch (SQLException e) {
            logger.error("登录过程中发生SQL异常: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
        } catch (Exception e) {
            logger.error("登录过程中发生未知异常: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "系统错误，请稍后重试");
        } finally {
            DBUtil.close(conn, ps, rs);
        }
        return result;
    }
} 